package crp.core.workflow.domain.services;

import com.qwlabs.cdi.DispatchInstance;
import com.qwlabs.cdi.Primary;
import crp.core.workflow.domain.events.WorkflowInstanceEnded;
import crp.core.workflow.domain.events.WorkflowInstanceStarted;
import crp.core.workflow.domain.events.WorkflowTaskEnded;
import crp.core.workflow.domain.events.WorkflowTaskStarted;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;

@ApplicationScoped
@Primary
public class WorkflowEventHandlerDispatcher implements WorkflowEventHandler {
    private final DispatchInstance<String, WorkflowEventHandler> dispatcher;

    @Inject
    public WorkflowEventHandlerDispatcher(Instance<WorkflowEventHandler> instance) {
        this.dispatcher = DispatchInstance.of(instance);
    }

    public void onEvent(WorkflowInstanceStarted event) {
        this.dispatcher.get(event.getContext().getTopic()).onEvent(event);
    }

    @Override
    public void onEvent(WorkflowInstanceEnded event) {
        this.dispatcher.get(event.getContext().getTopic()).onEvent(event);
    }

    @Override
    public void onEvent(WorkflowTaskStarted event) {
        this.dispatcher.get(event.getTopic()).onEvent(event);
    }

    @Override
    public void onEvent(WorkflowTaskEnded event) {
        this.dispatcher.get(event.getTopic()).onEvent(event);
    }
}
